package me.zhengjie.modules.equipment.service.impl;

import me.zhengjie.modules.equipment.domain.TEqptModel;
import me.zhengjie.modules.equipment.repository.TEqptModelRepository;
import me.zhengjie.modules.equipment.service.TEqptModelService;
import me.zhengjie.modules.equipment.service.dto.TEqptModelDTO;
import me.zhengjie.modules.equipment.service.dto.TEqptModelQueryCriteria;
import me.zhengjie.modules.equipment.service.mapper.TEqptModelMapper;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * Created by bruce on 2021/3/20.
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TEqptModelServiceImpl implements TEqptModelService{


    @Autowired
    private TEqptModelRepository tEqptModelRepository;

    @Autowired
    private TEqptModelMapper tEqptModelMapper;

    @Override
    public TEqptModelDTO create(TEqptModel resources) {
        return tEqptModelMapper.toDto(tEqptModelRepository.save(resources));
    }

    @Override
    public Object queryAll(TEqptModelQueryCriteria criteria, Pageable pageable) {
        Page<TEqptModel> page = tEqptModelRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tEqptModelMapper::toDto));
    }

    @Override
    public Object queryAll(TEqptModelQueryCriteria criteria) {
        return tEqptModelMapper.toDto(tEqptModelRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TEqptModelDTO findById(Integer id) {
        Optional<TEqptModel> tEqptModel = tEqptModelRepository.findById(id);
        ValidationUtil.isNull(tEqptModel,"TEqptModel","id",id);
        return tEqptModelMapper.toDto(tEqptModel.get());
    }

    @Override
    public void update(TEqptModel resources) {
        Optional<TEqptModel> optionalTEqptModel = tEqptModelRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTEqptModel,"TEqptModel","id",resources.getId());

        TEqptModel TEqptModel = optionalTEqptModel.get();
        // 此处需自己修改
        resources.setId(TEqptModel.getId());
        tEqptModelRepository.save(resources);
    }

    @Override
    public void delete(Integer id) {
        tEqptModelRepository.deleteById(id);
    }
}
